package com.hjxr.quota.valid;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLRecoverableException;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class ExceptionController extends ApiController {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>(2);
        bindingResult.getFieldErrors().forEach((item) -> {
            String field = item.getField();
            String errMsg = item.getDefaultMessage();
            map.put(field, errMsg);
        });
        return failed(JSON.toJSONString(map));
    }

    @ExceptionHandler(value = SQLRecoverableException.class)
    public R handleSQLRecoverableException(SQLRecoverableException sql) {
        String message = sql.getMessage();
        return failed(message);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleValidException(Exception e) {
        return R.failed(e.toString());
    }

}
